package edu.neu.cs6515.board.rules;

import edu.neu.cs6515.board.BoardCoord;
import edu.neu.cs6515.board.HexagonBoard;
import edu.neu.cs6515.xml.Placement;

/**
 * Verifies that each player starts with a placement adjecent to a distinct
 * default tile
 */
public final class LegalFirstMoveRule extends Rule {

    public static final String REASON = "ILLEGAL-FIRST-MOVE";

    /**
     * Init class with board obj
     * 
     * @param board
     *            the board to be used for validation
     */
    public LegalFirstMoveRule(final HexagonBoard board) {
        super(board);
    }

    @Override
    public boolean validate(final Placement p) {
        if (!board.isFirstRound()) {
            return true;
        } else {
            return checkUniqueStartHexagon(p);
        }
    }

    /**
     * @param p
     *            placement attempt
     * @return true if the placement is adjacent to a default hexagon that has
     *         "not been used yet"
     */
    private boolean checkUniqueStartHexagon(final Placement p) {
        final BoardCoord coord0 = p.getBoardCoord0();
        final BoardCoord coord1 = p.getBoardCoord1();

        for (final BoardCoord defaultHex : HexagonBoard.getAllDefaultHexagons()) {
            final boolean isNeighbor = board.isNeighbor(coord0, defaultHex)
            || board.isNeighbor(coord1, defaultHex);
            if (isNeighbor) {
                return (!board.getOccupiedDefaultHexagons().contains(defaultHex));
            }
        }
        return false;
    }

    @Override
    public String getReason() {
        return REASON;
    }
}
